//      main.c
//
//      Copyright 2011 richard <richard@desktop>
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.

// The 8 digit LCD display used PORTA multiplex to send data and select active cells.
// Bits 4 and 5 control the writing of the cell and cell select values when PORTA is written to.
//
// If bit 5 is set then the bit pattern if PORTA sets which cell is on.
// When a bit is cleared the cell is on. Rather anoyingly the bit pattern is reverse of the cell pos.
// That is the lsb sets the left most cell even though it is the right most bit.
//
// If bit 4 is set then the value in PORTA sets which led segments of cell are on. If the bit is cleared the segment is off.
//  ---
// |   |
//  ---
// |   |
//  ---   o
//
//   0
// 5   1
//   6
// 4   2
//   3     7
// Bit numbers for each cell.
#include "../common/common.h"


//Currently in data space, not program space.
static const unsigned char numbers[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d,0x07, 0x7f,0x6f};

u8 GetCharCode(char c)
{
	if( c >= '0' && c <= '9')
	{
		return numbers[c - 48];
	}
	return 0;
}

void printLCD(const char* text)
{
	u8 n = 0;
	for(n = 0 ; n < 8 ; n++)
	{
		//Seems senitive of stuff being done between setting the write bit, writing the value and clearing the bit.
		//So I get the char to write and the mask before I send the data.
		unsigned char c = GetCharCode(text[n]);
		unsigned char b = ~(1<<n);

		PORTD |= 1<<PD5;
		PORTA = b;//Bit pattern for which cell we are writing to.
		PORTD &= ~(1<<PD5);

		PORTD |= 1<<PD4;
		PORTA = c;//Value written.
		PORTD &= ~(1<<PD4);
		delay_ms(3);//Need a long time between chars else they start to effect each other. But no too long as it will flicker.
	}
}


int main(void)
{
 	//Set all port A and D.
	//Port A is used to send data, port D is for control of data to send.
	PORTA = 255;//Start with all off.
	DDRA = 255;

	PORTD = 255;//Start with all off.(bit 6 if off turns the sound on)
	DDRD = 255;

	char buf[8];
	memset(buf,0,8);
	u32 n = 0;
	/* loop forever */
	while (1)
	{
		n++;

		sprintf(buf,"%08ld",n);
		printLCD(buf);
	}
}













